using System;
using System.Threading;
using System.Threading.Tasks;
using Bean.Entity.Constant;
using Bean.Entity.Enum;
using Bean.Entity.Model;
using Bean.Entity.Param;
using Bean.Infrastructure;
using Bean.Service.IService;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Logical;

namespace Bean.PolicyBackend.Handler;

/// <summary>
/// 政策规则更新计划处理
/// 这里要做的事应该是将各个政策产品发送到对应的队列中去
/// 供消费者消费
/// </summary>
public class PolicyRuleUpdatePlanHandler : BackgroundService
{
    private ILogger<PolicyRuleUpdatePlanHandler> _logger;
    private readonly IPolicyPlanRuleTaskService _policyPlanRuleTaskService;
    private readonly IPolicySysRuleInfoService _policySysRuleInfoService;
    private readonly IPolicyKeyWordService _policyKeyWordService;

    public PolicyRuleUpdatePlanHandler(ILogger<PolicyRuleUpdatePlanHandler> logger,
        IPolicyPlanRuleTaskService policyPlanRuleTaskService, IPolicySysRuleInfoService policySysRuleInfoService,
        IPolicyKeyWordService policyKeyWordService)
    {
        _logger = logger;
        _policyPlanRuleTaskService = policyPlanRuleTaskService;
        _policySysRuleInfoService = policySysRuleInfoService;
        _policyKeyWordService = policyKeyWordService;
    }

    /// <summary>
    /// 执行
    /// </summary>
    /// <param name="stoppingToken"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        try
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                Console.WriteLine($"进来了");
                // await Task.Delay(5000, stoppingToken);
                // 扫描需要更新的产品计划
                // 根据政策发布订阅到对应的频道
                var taskList = await _policyPlanRuleTaskService.GetPolicyPlanTasksAsync(new PolicyRuleTaskParam()
                {
                    SID = 15063,
                    Status = PolicyTaskStatusEnum.Wait
                });

                var ruleIds = taskList.Select(s => s.RuleId).ToList();

                var policySysRuleInfoList = await _policySysRuleInfoService.GetListAsync(ruleIds);

                var policyKeyWords = taskList.Select(s => s.PolicyKeyWord).ToList();
                var policyKeyWordList = await _policyKeyWordService.GetListAsync(policyKeyWords);


                foreach (var taskItem in taskList)
                {
                    // 将任务变更为处理中
                    // await _policySysRuleInfoService.UpdateStatusAsync(taskItem.RuleId, 3);

                    var ruleInfo = policySysRuleInfoList.FirstOrDefault(s => s.SysPolicyRuleId == taskItem.RuleId);

                    if (ruleInfo == null)
                    {
                        // _logger.LogWarning();
                        continue;
                    }

                    var productQueue = new RedisQueue(PolicyConstant.PolicyCodeQueue(taskItem.PolicyKeyWord));
                    // 发送到队列
                    if (taskItem.OperateType is PolicyPlanOperateTypeEnum.Delete or PolicyPlanOperateTypeEnum.Disable)
                    {
                        // // 这里应该是全量政策删除
                        //     var policyDeleteCode = new PolicyKeyWordModel(taskItem.PolicyKeyWord).GetPolicyKeyCode();
                        //     RedisQueue = new RedisQueue(policyDeleteCode);
                        // 服务商ID
                        // 运价字典
                        // 采购商编码

                        var task = new PolicyProductTaskDto
                        {
                            TaskId = taskItem.RulePolicyTaskId,
                            OperateType = PolicyOTAOperateTypeEnum.Delete,
                            RuleText = taskItem.RuleText,
                            AirCode = taskItem.AirLine,
                            SerialNo = Guid.NewGuid().ToString(), //taskItem.SerialNo,
                            faretypeDic = ruleInfo.FareTypesDic,
                            SPCodes = ruleInfo.SPCode,
                            PolicyKeyWord = taskItem.PolicyKeyWord,
                            exhibitDic = ruleInfo.ExhibitDic,
                        };

                        productQueue.Send(JsonConvert.SerializeObject(task));
                    }
                    else if (taskItem.OperateType is PolicyPlanOperateTypeEnum.Update or PolicyPlanOperateTypeEnum.Enable)
                    {
                        var task = new PolicyProductTaskDto
                        {
                            TaskId = taskItem.RulePolicyTaskId,
                            OperateType = PolicyOTAOperateTypeEnum.DeleteAndUpload,
                            SerialNo = Guid.NewGuid().ToString(), //taskItem.SerialNo,
                            faretypeDic = ruleInfo.FareTypesDic,
                            SPCodes = ruleInfo.SPCode,
                            PolicyKeyWord = taskItem.PolicyKeyWord,
                            exhibitDic = ruleInfo.ExhibitDic,
                        };

                        productQueue.Send(JsonConvert.SerializeObject(task));
                    }

                    // 将任务变更为 处理完成
                    // await _policySysRuleInfoService.UpdateStatusAsync(taskItem.RuleId, 3);
                    
                    Console.WriteLine($"结束");
                   await Task.Delay(3000);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        finally
        {
            Console.WriteLine($"结束");
            Task.Delay(3000);
        }
    }
}